﻿using System.Data;
using System.Windows.Forms;
using Util.Database;

namespace ConfigureNZBLoader.TreeItemTags
{
    class Show : BaseTreeItemTag
    {
        public Show(long ID) : base(ID)
        {
        }

        public override EditControls.BaseEditControl EditControl
        {
            get
            {
                if (ID == 0)
                {
                    return null;
                }
                EditControls.Show c = new EditControls.Show();
                c.Open(ID);
                return c;
            }
        }

        public override TreeNode CreateNew(System.Windows.Forms.ContextMenuStrip menuNew, System.Windows.Forms.ContextMenuStrip menuDelete)
        {
            long ShowId;
            TreeNode t = new TreeNode("New show", 2, 2);
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "insert into show(name, detailsquery, namequery) values ('', '', '')";
                cmd.ExecuteNonQuery();

                cmd.CommandText = "select max(id) from show";
                ShowId = (long)cmd.ExecuteScalar();
                t.Tag = new Show(ShowId);
            }
            t.ContextMenuStrip = menuDelete;
            TreeNode t2 = new TreeNode("Requests");
            t2.Tag = new DownloadRequest(0, ShowId);
            t2.ContextMenuStrip = menuNew;
            t.Nodes.Add(t2);
            t2 = new TreeNode("Already downloaded");
            t2.Tag = new DownloadedEpisode(0, ShowId);
            t2.ContextMenuStrip = menuDelete;
            t.Nodes.Add(t2);
            return t;
        }

        public override void Delete()
        {
            using (IDbCommand cmd = DB.CreateCommand())
            {
                using (IDbTransaction t = cmd.Connection.BeginTransaction())
                {
                    cmd.Transaction = t;
                    cmd.CommandText = "delete from show where id=?";
                    IDataParameter par = cmd.CreateParameter();
                    par.Value = ID;
                    cmd.Parameters.Add(par);
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "delete from downloaded where id_show=?";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "delete from request where id_show=?";
                    cmd.ExecuteNonQuery();
                    t.Commit();
                }
            }
        }
    }
}
